package org.ruanjj.multithread.JUC;

import java.util.concurrent.atomic.AtomicStampedReference;

//解决ABA的问题
public class AtomicStampReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        //这里加了个版本进行比较处理
        AtomicStampedReference<Integer> integerAtomicReference = new AtomicStampedReference(100,1);

        new Thread(()->{
            int stamp = integerAtomicReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"获取到的版本为"+stamp);
            System.out.println(Thread.currentThread().getName()+"获取到的值是"+integerAtomicReference.getReference());

            //先把100改成101
            boolean result1 = integerAtomicReference.compareAndSet(100, 101, stamp, stamp+1);
            System.out.println(Thread.currentThread().getName()+"修改成功否"+result1);

            //后又把101改回去了
            boolean result2 = integerAtomicReference.compareAndSet(101,100,stamp+1,stamp+2);
            System.out.println(Thread.currentThread().getName()+"修改成功否"+result2);

        },"t1").start();

        new Thread(()->{
            int stamp = integerAtomicReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"获取到的版本为"+stamp);
            System.out.println(Thread.currentThread().getName()+"获取到的值是"+integerAtomicReference.getReference());
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //先把100改成101，模拟在B线程无感知的情况下，A线程已经把原值从100改到了101又改到了100
            boolean result1 = integerAtomicReference.compareAndSet(100, 101,stamp,stamp+1);
            System.out.println(Thread.currentThread().getName()+"修改成功否"+result1);

        },"t2").start();

        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"修改之后的值是"+integerAtomicReference.getReference());

    }
}
